/**
 * 
 */
package com.maywide.jdp.system.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.core.vo.Page;
import com.maywide.jdp.system.annotation.JSON;
import com.maywide.jdp.system.bean.ButtonBean;
import com.maywide.jdp.system.entities.Button;
import com.maywide.jdp.system.entities.Module;
import com.maywide.jdp.system.entities.Role;
import com.maywide.jdp.system.utils.JSONEditor;
import com.maywide.jdp.system.vo.ModuleButtonTree;

/**
 * 按钮管理Service
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Controller("buttonService")
public class ButtonServiceImpl implements ButtonService {
	private static final String APP_TYPE_BASE = "base";
	private static final String APP_TYPE_ROLES = "roles";
	/**
	 * 按钮管理Bean接口
	 */
	private ButtonBean bean = null;

	/**
	 * @param bean
	 *            the bean to set
	 */
	@Autowired
	@Qualifier("buttonBean")
	public void setBean(ButtonBean bean) {
		this.bean = bean;
	}

	@JSON
	@RequestMapping("/system/button/insert.json")
	@Override
	public Button insert(@RequestParam(value = "button") Button button,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.insert(button);
		return button;
	}

	@JSON
	@RequestMapping("/system/button/update.json")
	@Override
	public Button update(@RequestParam(value = "button") Button buttonVO,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = buttonVO.getId();
		Button button = (Button) bean.load(id);

		// 取得不可改变属性
		Module module = button.getModule();

		buttonVO.setModule(module);
		BeanUtils.copyProperties(buttonVO, button);

		bean.update(button);
		return button;
	}

	@JSON
	@RequestMapping("/system/button/updateApp.json")
	@Override
	public Button updateApp(@RequestParam(value = "button") Button buttonVO,
			@RequestParam(value = "appType") String appType,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = buttonVO.getId();

		if (appType.equals(APP_TYPE_BASE)) {
			// 取得不可改变属性
			Button button = (Button) bean.load(id);
			Module module = button.getModule();
			List<Role> roles = button.getRoles();

			buttonVO.setModule(module);
			buttonVO.setRoles(roles);
			BeanUtils.copyProperties(buttonVO, button);

			bean.update(button);
			return button;
		} else if (appType.equals(APP_TYPE_ROLES)) {
			List<Role> roles = buttonVO.getRoles();
			Button button = (Button) bean.load(id);
			button.setRoles(roles);
			bean.update(button);
			return button;
		} else {
			throw new AppException("未知的应用类型!");
		}
	}

	@JSON
	@RequestMapping("/system/button/load.json")
	@Override
	public Button load(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Button button = (Button) bean.load(id);
		return button;
	}

	@RequestMapping("/system/button/lock.json")
	@Override
	public void lock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.lock(id);
	}

	@RequestMapping("/system/button/unlock.json")
	@Override
	public void unlock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.unlock(id);
	}

	@RequestMapping("/system/button/move.json")
	@Override
	public void move(@RequestParam(value = "ids") List<String> ids,
			@RequestParam(value = "targetID") String targetID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.move(ids, targetID);
	}

	@JSON
	@RequestMapping(value = "/system/button/page.json")
	public Page page(
			@RequestParam(value = "first", defaultValue = "0") int first,
			@RequestParam(value = "limit", defaultValue = "20") int limit,
			@RequestParam(value = "sort", required = false) String sort,
			@RequestParam(value = "dir", required = false) String dir,
			@RequestParam(value = "moduleID", required = false) String moduleID,
			@RequestParam(value = "key", required = false) String key,
			@RequestParam(value = "active", required = false) String active,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "handle", required = false) String handle,
			@RequestParam(value = "serverClass", required = false) String serverClass,
			@RequestParam(value = "serverFunction", required = false) String serverFunction,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();

		if (key != null) {
			key = new StringBuffer("%").append(key).append("%").toString();
			conditions.put("key", key);
		}

		if (active != null)
			conditions.put("active", Boolean.parseBoolean(active));

		if (moduleID != null && !"button_root".equals(moduleID))
			conditions.put("moduleID", moduleID);

		if (code != null) {
			code = new StringBuffer("%").append(code).append("%").toString();
			conditions.put("code", code);
		}
		if (name != null) {
			name = new StringBuffer("%").append(name).append("%").toString();
			conditions.put("name", name);
		}
		if (handle != null) {
			handle = new StringBuffer("%").append(handle).append("%")
					.toString();
			conditions.put("handle", handle);
		}
		if (serverClass != null) {
			serverClass = new StringBuffer("%").append(serverClass).append("%")
					.toString();
			conditions.put("serverClass", serverClass);
		}
		if (serverFunction != null) {
			serverFunction = new StringBuffer("%").append(serverFunction)
					.append("%").toString();
			conditions.put("serverFunction", serverFunction);
		}

		return bean.page(first, limit, sort, dir, conditions, null);
	}

	@JSON
	@RequestMapping(value = "/system/button/treeGrid.json")
	public List<ModuleButtonTree> treeGrid(@RequestParam(value = "parentID") String parentID,
			@RequestParam(value = "rootID", required = false) String rootID,
			@RequestParam(value = "roleID", required = false) String roleID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();

		if (parentID != null && !"module_button_root".equals(parentID))
			conditions.put("parentID", parentID);

		if (rootID != null)
			conditions.put("rootID", rootID);

		if (roleID != null)
			conditions.put("roleID", roleID);

		Context context = (Context) session.getAttribute("context");
		String[] roleIDs = context.getRoleIDs();
		if (roleIDs != null)
			conditions.put("roleIDs", roleIDs);

		return bean.treeGrid(conditions, null);
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Button.class, new JSONEditor(Button.class));
	}
}
